﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class Register : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //检查两个字段是不是有数据的。
            if (Request.Form["lb"] != null && Request.Form["username"] != null)
            {
                //有数据的时候清空所有内容。
                Response.Clear();
                string sType = Request.Form["lb"].ToString();
                string sUserName = Request.Form["username"].ToString();
                //第一种类型，检查用户名是否存在
                if (sType == "checkname")
                {
                    //查找到的用户名大于0个
                    if (Membership.FindUsersByName(sUserName).Count > 0)
                        Response.Write("false");
                    else
                        Response.Write("true");                    
                }
                else if (sType == "adduser")
                {
                    string sEmail = Request.Form["email"].ToString();
                    string sConfirm = Request.Form["confirm"].ToString();
                    string sPassword=Request.Form["password"].ToString();
                    //检查验证码
                    if (Session["CheckCode"].ToString() != sConfirm)
                    {
                        Response.Write("验证码错误！");
                    }
                    else
                    {
                        try
                        {
                            Membership.CreateUser(sUserName, sPassword, sEmail);
                            addUser(sUserName, sEmail);

                            Response.Write("注册成功");
                        }
                        catch (Exception ex)
                        {
                            Response.Write(ex.Message);
                        }
                    }
                }
                Response.End();
            }
        }
    }
    //数据库中添加用户
    public void addUser(string sUserName,string sEmail)
    {
        SqlDataSource ds = new SqlDataSource();
        ds.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ls_Database"].ToString();
        ds.InsertCommand = "insert into ls_User(User_Name,User_Email) values(@username,@email)";
        ds.InsertParameters.Add("username", sUserName);
        ds.InsertParameters.Add("email", sEmail);
        ds.Insert();
        ds.Dispose();
    }

}
